/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.xxl.adapter.dao;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.xxl.adapter.core.XxlConvert;
import com.xxl.adapter.entity.JobUser;
import com.xxl.adapter.repository.JobUserRepository;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.dao.XxlJobUserDao;
import java.util.List;
import javax.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Component;

/**
 * XxlJobUserDaoImpl
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class JobUserDaoImpl implements XxlJobUserDao, XxlConvert {

  @Autowired private JobUserRepository repository;

  public Page<JobUser> page(int offset, int pagesize, String username, int role) {
    return repository.findAll(
        ((root, query, cb) -> {
          Predicate predicate = cb.conjunction();
          if (StrUtil.isNotBlank(username)) {
            predicate.getExpressions().add(cb.like(root.get("username"), "%" + username + "%"));
          }
          if (role > -1) {
            predicate.getExpressions().add(cb.equal(root.get("role"), role));
          }

          return predicate;
        }),
        PageRequest.of(
            offset, pagesize, Sort.by(CollectionUtil.newArrayList(Order.asc("username")))));
  }

  @Override
  public List<XxlJobUser> pageList(int offset, int pagesize, String username, int role) {
    Page<JobUser> page = this.page(offset, pagesize, username, role);
    return this.convert(XxlJobUser.class, page.getContent());
  }

  @Override
  public int pageListCount(int offset, int pagesize, String username, int role) {
    Page<JobUser> page = this.page(offset, pagesize, username, role);
    return (int) page.getTotalElements();
  }

  @Override
  public XxlJobUser loadByUserName(String username) {
    return this.convert(
        XxlJobUser.class,
        repository.findAll((root, query, cb) -> cb.equal(root.get("username"), username)).stream()
            .findFirst()
            .orElse(null));
  }

  @Override
  public int save(XxlJobUser xxlJobUser) {
    JobUser jobUser = repository.save(this.convert(JobUser.class, xxlJobUser));
    xxlJobUser.setId(jobUser.getId());
    return jobUser.getId();
  }

  @Override
  public int update(XxlJobUser xxlJobUser) {
    int id = xxlJobUser.getId();
    JobUser jobUser = repository.findById(id).orElse(null);
    if (jobUser != null) {
      if (StrUtil.isNotBlank(xxlJobUser.getPassword())) {
        jobUser.setPassword(xxlJobUser.getPassword());
      }
      jobUser.setRole(xxlJobUser.getRole());
      jobUser.setPermission(xxlJobUser.getPermission());

      repository.save(jobUser);
    }

    return id;
  }

  @Override
  public int delete(int id) {
    repository.deleteById(id);
    return id;
  }

  @Override
  public Logger getLogger() {
    return log;
  }
}
